/* 
 * timer_checkboxes
 */

// Note if only sending messages see oscP5flush

import oscP5.*;
import netP5.*;
import controlP5.*;

ControlP5 cp5;
OscP5 oscP5;


NetAddress naServerAddr;

int srvrSock = 9001;

CheckBox checkbox1;
CheckBox checkbox2;

ControlTimer cTimer;

int time0, beatIx = 0;


void setup() {
  size(400,400);
   
  oscP5 = new OscP5(this,srvrSock);
  naServerAddr = new NetAddress("127.0.0.1", srvrSock); 
  
  cp5 = new ControlP5(this);
  
  checkbox1 = cp5.addCheckBox("checkbox1")
                 .setPosition(10, 200)
                 .setColorForeground(color(120))
                 .setColorActive(color(255))
                 .setColorLabel(color(255))
                 .setSize(40, 40)
                 .setItemsPerRow(8)
                 .setSpacingRow(0)
                 .addItem("a1", 1)
                 .addItem("a2", 2)
                 .addItem("a3", 4)
                 .addItem("a4", 8)
                 .addItem("a5", 16)
                 .addItem("a6", 32)
                 .addItem("a7", 64)
                 .addItem("a8", 128)
                 .hideLabels()
                 ;

  checkbox2 = cp5.addCheckBox("checkbox2")
                 .setPosition(10, 260)
                 .setColorForeground(color(120))
                 .setColorActive(color(250))
                 .setColorLabel(color(250))
                 .setSize(40, 40)
                 .setItemsPerRow(8)
                 .setSpacingRow(0)
                 .addItem("b1", 1)
                 .addItem("b2", 2)
                 .addItem("b3", 4)
                 .addItem("b4", 8)
                 .addItem("b5", 16)
                 .addItem("b6", 32)
                 .addItem("b7", 64)
                 .addItem("b8", 128)
                 .hideLabels()
                 ;
  cTimer = new ControlTimer();
  
}

void draw() {
  background(176,196,222);  
  int tnow = millis();
  if ((tnow - time0) >= 500)
  { 
    println("1 sec..." + beatIx);
    sendCheckerStatus(beatIx);
    time0 = tnow;
    if (beatIx + 1 < checkbox1.getItems().size()) { 
      beatIx += 1;
    } else {
      beatIx = 0;
    }
    
    
      
  }  
}

void checkbox1 (int theValue) {
  // empty 
}

void checkbox2 (int theValue) { 
  // empty
}

//int checkboxAns(CheckBox chk) {
//  int sum = 0;
//  for (int i = 0; i < chk.getItems().size(); i++)
//  {
//    if (chk.getItem(i).getState() ) { sum += pow(2,i) ;}
//  }  
//  return sum;
//}


void sendCheckerStatus(int i) {
  if (checkbox1.getItem(i).getState()) {  
    println("sending " + i );
    OscMessage msg = new OscMessage("/drum1");
    msg.add(1);
    oscP5.flush(msg,naServerAddr);
  } 
  if (checkbox2.getItem(i).getState()) {  
    println("sending " + i );
    OscMessage msg = new OscMessage("/drum1");
    msg.add(2);
    oscP5.flush(msg,naServerAddr);
  } 
  
  
}

// Checkboxes seem problematic for controlEvent.
// Even the example code has runtime failures.
